package com.qf.ability.message.handler;

import com.qf.ability.message.entity.Message;
import com.qf.ability.message.entity.Room;
import com.qf.ability.message.entity.UserSession;
import com.qf.ability.message.handler.base.BaseInChannelHandler;
import com.qf.ability.message.utils.RoomUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * author Ken
 * create_time 2022/10/19
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class SlaveCloseMsgInChannelHandler extends BaseInChannelHandler<Message> {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    protected boolean isSupport(Message msg) {
        return msg.getId().equals("slaveClose");
    }

    @Override
    protected void hander(ChannelHandlerContext ctx, Message msg) {
        Integer cid = msg.getCid();
        Integer uid = msg.getUid();

        Room room = RoomUtils.get(cid);
        UserSession userSession = room.getSlaves().remove(uid);
        if (userSession.getWebRtcEndpoint() != null) {
            userSession.getWebRtcEndpoint().release();
        }
        userSession.getChannel().close();


        //删除人数
        Long onlineCount = redisTemplate.opsForHash().increment("course_" + cid, "online_count", -1);
        //并且通知所有人
        //通知给房间其他人的消息
        Message message = new Message()
                .setId("onlineResult")
                .setContent(onlineCount);
        room.sendAll(message, true);
    }
}
